#include "tickcountrunnablewin.hpp"


TickCountRunnableWin::TickCountRunnableWin(QObject *parent) :
	TickCountRunnable(parent)
{
    LARGE_INTEGER frequency;

    // Check whether the high Resolution Timer is available
    m_useHighResolution = false;
    m_useHighResolution = QueryPerformanceFrequency(&frequency);
}


void TickCountRunnableWin::run()
{
    setIsRunning(true);

    // Set the current Threads processor affinity
    int affinity = property("id").toInt() % QThread::idealThreadCount();
    DWORD_PTR mask = pow(2, affinity - 1);
    SetThreadAffinityMask (GetCurrentThread(), mask);

    while (getIsRunning())
    {
	LARGE_INTEGER lastTickCount;
	LARGE_INTEGER currentTickCount;

	// Set the HighPart to Zero if there are no High Resolution Timers available
	if (!m_useHighResolution)
	{
	    lastTickCount.HighPart = 0;
	    currentTickCount.HighPart = 0;
	}

	// Get current Counter and store it
	if (m_useHighResolution)
	{
	    QueryPerformanceCounter(&lastTickCount);
	} else {
	    lastTickCount.LowPart = GetTickCount();
	}


	// Do a msleep()
	QThread::msleep(m_waitInterval);

	// Get the Counter after a msleep
	if (m_useHighResolution)
	{
	    QueryPerformanceCounter(&currentTickCount);
	} else {
	    currentTickCount.LowPart = GetTickCount();
	}

	// Calculate the difference
	int difference = 0;
	difference = currentTickCount.LowPart - lastTickCount.LowPart;
	qDebug() << objectName() << difference;
    }
}
